/**
 * util & format方法
 */
String.prototype.format = function () {
    var s = this, i = arguments.length;
    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};
/**
 *
 * @type {jQuery}
 */
var ajaxForm = function (e, fn) {
    e.ajaxForm({
        type: 'POST',
        dataType: 'JSON',
        timeout: 3000,
        success: function (data) {
            layer.msg('亲，操作成功了^_^');
            console.log(fn);
            if (fn) {
                console.log('reload table!');
                fn();
            }
            e.find('.btn-close').trigger('click');
        },
        error: function () {
            layer.alert('亲，操作失败了-_-', {
                icon: 2,
                offset: '120px'
            })
        }
    });
};

/**
 * ajax
 */
var ajaxReloadGrid = function (url, jsonParams, fn, type) {
    $.ajax({
        type: (type ? type : 'GET'),
        url: url,
        data: jsonParams,
        contentType: "application/json;charset=UTF-8",
        dataType: 'JSON',
        async: false,
        success: function (data) {
            console.log(data);
            layer.msg('操作成功，亲^_^', {
                offset: '120px'
            });
            if (fn) {
                fn();
            }
        },
        error: function (msg) {
            console.log(msg);
            layer.msg('亲，系统开小差了-_-', {
                offset: '120px'
            });
        }
    });
};

/**
 * ajax json style
 * @param url
 * @param jsonParams
 * @param type
 * @returns {{}}
 */
var ajaxJson = function (url, jsonParams, type) {
    var data = {};
    $.ajax({
        url: url,
        data: jsonParams,
        contentType: "application/json;charset=UTF-8",
        type: (type ? type : 'GET'),
        dataType: 'JSON',
        async: false,
        success: function (o) {
            console.log(o);
            data = o.data;
        },
        error: function (msg) {
            console.log(msg);
            layer.msg('亲，系统开小差了-_-');
        }
    });
    return data;
};

/**
 * 数组分割方法
 * @param array
 * @param subGroupLength
 * @returns {Array}
 */
function group(array, subGroupLength) {
    var index = 0;
    var newArray = [];

    while (index < array.length) {
        newArray.push(array.slice(index, index += subGroupLength));
    }

    return newArray;
};

/**
 * 从 url中获取指定参数
 * @param name
 * @returns {null}
 */
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}